import os
from datetime import datetime

import allure
from appium.webdriver.webdriver import WebDriver
from selenium.common import NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait

from tests.api_demo.utils import root_dir
from tests.api_demo.utils.black_handle import black_wrapper
from tests.api_demo.utils.log_util import logger


class BasePage:
    DEFAULT_IMPLICITLY = 10

    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    @black_wrapper
    def find(self, by, value=None):
        if isinstance(by, tuple):
            logger.debug(f"使用 {by[0]} 的定位方式,进行元素 {by[1]} 的定位")
            return self.driver.find_element(*by)
        logger.debug(f"使用 {by} 的定位方式,进行元素 {value} 的定位")
        return self.driver.find_element(by, value)

    @black_wrapper
    def finds(self, by, value=None):
        if isinstance(by, tuple):
            logger.debug(f"使用 {by[0]} 的定位方式,进行元素 {by[1]} 的定位")
            return self.driver.find_elements(*by)
        logger.debug(f"使用 {by} 的定位方式,进行元素 {value} 的定位")
        return self.driver.find_elements(by, value)

    def find_click(self, by, value=None):
        ele = self.find(by=by, value=value)
        ele.click()

    def find_send_keys(self, by, value=None, text=None):
        ele = self.find(by=by, value=value)
        logger.debug(f"进行信息{text}的输入操作")
        ele.send_keys(text)

    def wait(self, method, time_out=5):
        el = WebDriverWait(self.driver, time_out).until(method)
        return el

    def set_implicitly_wait(self, times=1):
        self.driver.implicitly_wait(times)

    def my_swip(self, duration=2000):
        size = self.driver.get_window_size()
        width = size["width"]
        height = size["height"]
        start_x = width * 0.5
        start_y = height * 0.8
        end_x = width * 0.5
        end_y = height * 0.2
        self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    def swip_find(self, by, value, max_count, duration=None):
        count = 0
        while count < max_count:
            try:
                ele = self.find(by=by, value=value)
                self.set_implicitly_wait(self.DEFAULT_IMPLICITLY)
                return ele
            except Exception as e:
                self.my_swip(duration)
                count += 1
        raise NoSuchElementException

    def get_time_name(self, dir_name, file_name):
        dir_path = f"{root_dir}/data/{dir_name}"
        os.makedirs(dir_path, exist_ok=True)
        return f'{dir_path}/{file_name}'

    def save_page_source(self):
        # 获取当前时间
        now = datetime.now()
        # 格式化时间，包含毫秒
        time_format = now.strftime('%m-%d-%H-%M-%S-%f')[:-3]
        html_data = self.driver.page_source
        path = self.get_time_name('page_source', f'PageSource{time_format}.html')
        with open(path, "w", encoding="utf-8") as f:
            f.write(html_data)
        allure.attach.file(path, attachment_type=allure.attachment_type.HTML)

    def save_screen_shot(self):
        # 获取当前时间
        now = datetime.now()
        # 格式化时间，包含毫秒
        time_format = now.strftime('%m-%d-%H-%M-%S-%f')[:-3]
        path = self.get_time_name('screen_shot', f'img{time_format}.png')
        self.driver.save_screenshot(path)
        allure.attach.file(path, attachment_type=allure.attachment_type.PNG)
